<script setup lang="ts">
import {h, onBeforeUnmount, onMounted, ref} from 'vue';
import { MdEditor } from 'md-editor-v3';
import 'md-editor-v3/lib/style.css';
import LayoutStore from '@/store/modules/setting.ts'
import {EyeOutlined, SaveOutlined, SendOutlined} from "@ant-design/icons-vue";
import artilceCategoryApi from '@/api/articleCategory.ts'
import {getToken} from "@/utils/tokenUtils.ts";
import articleApi from '@/api/article.ts'
import tagsApi from '@/api/tags.ts'
import {message} from "ant-design-vue";
import axios from "axios";
import {useRoute} from "vue-router";
const route = useRoute()
const layoutStore = LayoutStore()
const text = ref('Hello Editor!');
onMounted(() => {
  //将编辑状态改为 true
  layoutStore.setLayout1(true)
})
onBeforeUnmount(() => {
  //将编辑状态改为 false
  layoutStore.setLayout1(false)
})

const article = ref({
  title: '',
  categoryId: '',
  tagId: '',
  coverImg: '',
  content: '',
  articleAbstract: '',
  isPublic: 1,
  status: null
})
console.log(route.query)
if (route.query && route.query.id) {
  article.value = route.query
}
const resetArticle = () => {
  article.value = {
    title: '',
    categoryId: '',
    tagId: '',
    coverImg: '',
    content: '',
    articleAbstract: '',
    isPublic: 1,
    status: null
  }
}
//获取文章分类
const articleCategoryList = ref([])
onMounted(async() => {
  const result = await artilceCategoryApi.getAllArticleCategory()
  articleCategoryList.value = result.rows.map((item:any) => {
    return {
      label: item.name,
      value: item.id
    }
  })
})
//获取tags的树形结构
const tagsTree = ref([])
onMounted(async() => {
  const result = await artilceCategoryApi.getTagsTree()
  tagsTree.value = result.data.map((item:any) => {
    const value = {label:item.name,options:[]}
    const children = item.tagsList.map((v:any) => {
      return {
        label: v.name,
        value: v.id
      }
    })
    value.options = children
    return value
  })
})
const handleChange = ((event:any) => {
  console.log(event)
  if (event.file?.response?.code == 200) {
    article.value.coverImg = event.file?.response?.data
  }
});
const loading = ref<boolean>(false);
//是否是预览状态
const isPreview = ref<boolean>(false);
const md = ref<any>(null)
const previewHandle = () =>  {
  if (md.value) {
    md.value.togglePreview(!isPreview.value); // 调用暴露的方法
  }
  isPreview.value = !isPreview.value; // 切换预览状态
};
// 保存 / 发布
const validateFiled = () => {
  if (!article.value.title) {
    return '文章标题不能为空'
  }
  if (!article.value.categoryId) {
    return '文章分类不能为空'
  }
  if (!article.value.tagId) {
    return '文章标签不能为空'
  }
  if (!article.value.coverImg) {
    return '文章封面图不能为空'
  }
  if (!article.value.articleAbstract) {
    return '文章摘要不能为空'
  }
  if (!article.value.content) {
    return '文章内容不能为空'
  }
 }

const save = async (status:any) => {
  const result = validateFiled();
  if (result) {
    message.error(result)
    return
  }
  article.value.status = status
  const response = await articleApi.saveArticle(article.value);
  if (response.code == 200) {
    if (status == 1){
      message.success('文章保存成功')
    } else {
      message.success('文章发布成功，待管理员审核')
    }
    resetArticle()
  }
  else{
    message.error('文章保存失败')
  }
}

const onUploadImg = async (files:any, callback:any) => {
  const res = await Promise.all(
      files.map((file:any) => {
        return new Promise((rev, rej) => {
          const form = new FormData();
          form.append('file', file);

          axios
              .post('dev-api/client/user/file/upload', form, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'authorization': 'Bearer ' + getToken()
                },
              })
              .then((res) => rev(res))
              .catch((error) => rej(error));
        });
      })
  );

  // 方式一
  callback(res.map((item) => item.data.data));

  // 方式二
  // callback(
  //   res.map((item: any) => ({
  //     url: item.data.url,
  //     alt: 'alt',
  //     title: 'title'
  //   }))
  // );
};
</script>

<template>
  <div class="editor">
    <MdEditor
        ref="md"
        :preview="false"
        @onUploadImg="onUploadImg"
        v-model="article.content" class="left"/>
    <a-card class="right">
      <template #title>
        文章设置
      </template>
      <div class="title">
        文章标题
      </div>
      <a-input v-model:value="article.title"
               :status="article.title ? '' : 'error'"
               placeholder="请输入文章标题"
               class="content"/>
      <div class="title">
        分类
      </div>
      <a-select
          v-model:value="article.categoryId"
          show-search
          placeholder="Select a person"
          style="width: 200px"
          :options="articleCategoryList"
          @change="handleChange"
          :status="article.categoryId ? '' : 'error'"
          class="content"
      ></a-select>
      <div class="title">
        标签
      </div>
      <a-select
          v-model:value="article.tagId"
          :options="tagsTree"
          style="width: 200px"
          :status="article.tagId ? '' : 'error'"
          @change="handleChange"
      ></a-select>
      <div class="title">
        封面图
      </div>
      <a-upload
          name="file"
          list-type="picture-card"
          class="avatar-uploader content"
          :show-upload-list="false"
          :headers="{
            authorization: 'Bearer ' + getToken()
          }"
          action="dev-api/client/user/file/upload"
          @change="handleChange"
      >
        <img v-if="article.coverImg" :src="article.coverImg" alt="avatar" />
        <div v-else>
          <loading-outlined v-if="loading"></loading-outlined>
          <plus-outlined v-else></plus-outlined>
          <div class="ant-upload-text">点击上传封面图</div>
        </div>
      </a-upload>
      <div class="title">
        文章摘要
      </div>
      <a-textarea v-model:value="article.articleAbstract"
                  placeholder="输入文章摘要"
                  show-count :maxlength="100"
                  class="content"
                  style="height: 100px"/>
      <div class="title">
        发布设置
      </div>
      <a-radio-group
          v-model:value="article.isPublic"
          class="content"
          name="radioGroup">
        <a-radio :value="1">公开</a-radio>
        <a-radio :value="2">私密</a-radio>
      </a-radio-group>
      <div class="content-button">
        <a-button
            :icon="h(EyeOutlined)"
            class="button"
            @click="previewHandle"
            :danger="isPreview"
        >
          {{isPreview ? '取消预览' : '预览' }}
        </a-button>
        <a-button
            :icon="h(SaveOutlined)"
            class="button"
            @click="save(1)"
        >
          保存草稿
        </a-button>
        <a-button
            type="primary"
            :icon="h(SendOutlined)"
            class="button"
            @click="save(2)"
        >
          发布文章
        </a-button>
      </div>
    </a-card>
  </div>
</template>
<style scoped lang="scss">

.editor{
  display: flex;
  gap: 5%;
  height: 100%;
  width: 100%;
  .left{
    flex: 2;
  }
  .right{
    flex: 0.5;
    .title{
      font-size: 16px;
      margin-bottom: 5px;
    }
    .content{
      margin-bottom: 10px;
    }
    .content-button{
      margin-bottom: 10px;
      display: grid;
      grid-template-rows: 3;
      gap: 5px;
    }
  }
  :deep(.md-editor){
    height: 100%;
  }
  :deep(.md-editor-toolbar-wrapper){
    *{
      box-sizing: content-box;
    }
  }
}
</style>
